using System;
using System.IO;
using EmbeddedWebserver.Core;
using EmbeddedWebserver.Core.Handlers.Abstract;

using EmbeddedWebserver.Core.Json;
using SolarDevices;

namespace SolarWeb
{
    class CalendarEventsHandler : HandlerBase
    {
        #region Non-public members

        protected override void ProcessRequestWorker(HttpContext pContext)
        {
            switch (pContext.Request.Method)
            {
                case HttpMethods.GET:
                    var start = pContext.Request.QueryString["start"];
                    var end = pContext.Request.QueryString["end"];
                    var startDt = FromUnixTime(Convert.ToInt64(start));
                    var endDt = FromUnixTime(Convert.ToInt64(end));
                    var el = EventLogger.GetLogger();
                    var events = el.GetEvents(startDt, endDt);
                    var formatter = new JsonFormatter();
                    pContext.Response.ResponseBody = formatter.ToJson(events);
                    pContext.Response.ContentType = "application/json";
                    break;
            }
        }

        public DateTime FromUnixTime(long unixTime)
        {
            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return epoch.AddSeconds(unixTime);
        }

        public static long ToUnixTime(DateTime date)
        {
            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            var ticks = (date - epoch).Ticks;
            return ticks / TimeSpan.TicksPerSecond;
        }

        #endregion

        #region Constructors

        public CalendarEventsHandler() : base(HttpMethods.GET) { }

        #endregion
    }


}
